<template>
	<view class="wrap">
		<view class="selectCondition" style="background-color: white;" v-show="false">
			<view class="search" @click="searchOragins">
				<u-search :show-action="false" :clearabled="true" v-model="orgins" placeholder="请选择厂站"></u-search>
				<u-select v-model="showOragins" :list="station" @confirm="confirmOrgin"></u-select>
			</view>
			<view class="search" @click="searchState">
				<u-search mode="single-column" :show-action="false" v-model="statuss" placeholder="请选择状态"></u-search>
				<u-select v-model="showStates" :list="states" @confirm="confirmState"></u-select>
			</view>
			<view class="selectItem">
				<u-button @click="searchQeuipmentInfo" class="searchButton" type="primary" size="mini"
					shape="square">查询</u-button>
			</view>
		</view>


		<u-search @clear='searchClear' :clearabled="true" placeholder="请输入设备名称" v-model="equipName"
			@custom="searchEqName" @search="searchEqName"></u-search>


		<view @click="open()" class="sift">
			<span>智能排序</span>
			<u-icon v-if="this.showIcon" name="arrow-down-fill" size="18"></u-icon>
			<u-icon v-if="!this.showIcon" name="arrow-up-fill" size="18"></u-icon>
		</view>

		<u-popup v-model="showPopup" @close='close' mode="left" width="500rpx" height="600px">

			<view class="popup-container">

			<view class="info-box">
			    <view :class="{ active: activeDetail === 'equipmentTypecode', 'with-bar': activeDetail === 'equipmentTypecode' }"
			        @click="selectDetail('equipmentTypecode')">
			        设备类型
			    </view>
			    <view :class="{ active: activeDetail === 'parentName', 'with-bar': activeDetail === 'parentName' }"
			        @click="selectDetail('parentName')">
			        安装位置
			    </view>
			    <view :class="{ active: activeDetail === 'status', 'with-bar': activeDetail === 'status' }"
			        @click="selectDetail('status')">
			        状态
			    </view>
			    <view :class="{ active: activeDetail === 'networkStatus', 'with-bar': activeDetail === 'networkStatus' }"
			        @click="selectDetail('networkStatus')">
			        网络状态
			    </view>
			</view>

				<view>
					<view v-for="(item, index) in filteredEquipInfo" :key="index" class="details-box"
						:class="{ selected: isSelected(item.value) }" @click="selectItem(item.value,item.key)">
						{{ item.value }}
					</view>
				</view>


			</view>
			<view class="details-button">
				<u-button @click="reset" type="primary" shape="circle" size="mini">重置</u-button>
			</view>

		</u-popup>


		<scroll-view class="scroll-list" scroll-y="true">

			<view class="view-container">
				<view class="header" v-for="item in equipInfo" :key="item.id" @click="details(item.id)">
					<view class="status-avatar">
						<view v-if="item.status==1" class="status-badge status-1">异常</view>
						<view v-else-if="item.status==2" class="status-badge status-2">运行</view>
						<view v-else-if="item.status==3" class="status-badge status-3">停止</view>
						<view v-else class="status-badge status-4">维修维护</view>
						<u-avatar class="avatar" :size="106" :src="item.image"></u-avatar>
					</view>
					<view class="details">
						<view>
							<!-- <view :style="{ color: item.isAlarm > 0 ? 'red' : 'black' }"> -->
							{{ item.equipment_name }}
						</view>
						<view><span>安装位置：</span>{{item.parent_name}}</view>
						<view><span>设备编号：</span>{{item.equip_id}}</view>
						<view><span>设备型号：</span>{{item.usetime}}</view>
					</view>

					<view class="status-container">
						<view class="status-alarm">
							<image v-if="item.isAlarm>0" style="width: 32rpx;height: 28rpx"
								src="~@/static/aidex/falarm.png" mode=""></image>
						</view>

						<view class="status-icon">
							<u-icon :name="item.network_status == 0 ? 'wifi-off' : 'wifi'" color="#2979ff" size="28">
							</u-icon>
						</view>

					</view>


				</view>
				<u-divider v-if="this.loading">已经到底了</u-divider>
				<u-divider v-else-if="!this.loading">正在加载中</u-divider>
			</view>
		</scroll-view>

	</view>
</template>
<script>
	import searchFalarmVue from '../../../components/headsearch/searchFalarm.vue';
	export default {
		data() {
			return {
				equipInfoOne: [],
				selectedItem: null,
				selectedKey: null,
				activeDetail: "equipmentTypecode",
				showPopup: false,
				showIcon: false,
				loading: false,
				showOragins: false,
				showStates: false,
				orgins: '',
				statuss: '',
				station: [{
					value: '',
					label: ''
				}, ],
				networkStatusMap: {
					'0': '离线',
					'1': '在线'
				},
				states: [{
						value: '2',
						label: '运行'
					},
					{
						value: '3',
						label: '停止'
					},
					{
						value: '1',
						label: '异常'
					},
					{
						value: '4',
						label: '维修维护'
					}

				],
				originId: '',
				equipStatus: '',
				equipName: '',
				headOrgin: 0,
				//设备列表信息
				equipInfo: [],
				//筛选列表信息
				equipInfo2: [],
				equipmentTypecode: "",
				networkStatus: '',
				parentName: ''
			}
		},
		onLoad() {
			this.getOrginList();
			this.searchQeuipmentInfo2();
		},
		computed: {
			filteredEquipInfo() {
				const uniqueValues = new Map();
				const detailMap = {
					'equipmentTypecode': 'equipment_typecode',
					'status': 'status',
					'networkStatus': 'network_status',
					'parentName': 'parent_name'
				};
				const detailField = detailMap[this.activeDetail];

				if (detailField) {
					this.equipInfo2.forEach(item => {
						if (item[detailField]) {
							let value = item[detailField];
							let key = detailField;
							console.log(key, value)
							if (this.activeDetail === 'networkStatus') {
								value = this.networkStatusMap[value] || value;
							} else if (this.activeDetail === 'status') {
								value = this.getStateLabel(value);
							}

							if (!uniqueValues.has(value)) {
								uniqueValues.set(value, key);
							}
						}
					});
				}
				return Array.from(uniqueValues, ([value, key]) => ({
					value,
					key
				}));
			}
		},


		methods: {
			reset() {
				this.equipStatus = '';
				this.networkStatus = '';
				this.equipmentTypecode = '';
				this.parentName = "";
				this.selectedItem = "";
				this.showIcon = false;
				this.showPopup = false;
				this.searchQeuipmentInfo();
			},
			selectItem(value, key) {
				this.selectedItem = value;
				this.selectedKey = key
				this.showIcon = false;
				this.showPopup = false;
				if (this.selectedKey === 'equipment_typecode') {
					this.equipmentTypecode = this.selectedItem;
					this.networkStatus = "";
					this.equipStatus = "";
					this.parentName = "";
				} else if (this.selectedKey === 'status') {
					const state = this.states.find(state => state.label === this.selectedItem);
					// 将找到的状态对象的 label 赋值给 equipStatus
					this.equipStatus = state ? state.value : '未知状态';
					this.equipmentTypecode = "";
					this.networkStatus = "";
					this.parentName = "";
				} else if (this.selectedKey === 'network_status') {
					const reverseNetworkStatusMap = Object.fromEntries(
						Object.entries(this.networkStatusMap).map(([key, value]) => [value, key])
					);
					this.networkStatus = reverseNetworkStatusMap[value];
					this.equipmentTypecode = "";
					this.equipStatus = "";
					this.parentName = "";
				} else {
					this.parentName = this.selectedItem;
					this.equipmentTypecode = "";
					this.networkStatus = "";
					this.equipStatus = "";
				}
				this.searchQeuipmentInfo()

			},
			isSelected(value) {
				return this.selectedItem === value;
			},
			getStateLabel(value) {
				const state = this.states.find(state => state.value === value);
				return state ? state.label : value;
			},
			selectDetail(detail) {
				this.activeDetail = detail;
			},
			open() {
				this.showPopup = true;
				this.showIcon = true;
			},
			close() {
				this.showIcon = false;
				this.showPopup = false;
			},
			search(value) {
				this.$u.toast('搜索内容为：' + value)
			},
			searchOragins() {
				this.showOragins = true;
				if (this.orgins.length != 0) {
					this.showOragins = false;
					this.originId = '';
				}
			},
			searchClear() {
				this.equipName = ''
				this.searchQeuipmentInfo()
			},
			searchState() {
				this.showStates = true;
				if (this.statuss.length != 0) {
					this.showStates = false;
					this.equipStatus = '';
					return;
				}
			},
			searchEqName(e) {
				this.equipStatus = '';
				this.networkStatus = '';
				this.equipmentTypecode = '';
				this.parentName = "";
				this.selectedItem = "";
				this.showIcon = false;
				this.showPopup = false;
				this.equipName = e
				this.searchQeuipmentInfo()
			},
			confirmOrgin(e) {
				e.map((val, index) => {
					this.orgins = val.label;
					this.originId = val.value;
				})
			},
			confirmState(e) {
				e.map((val, index) => {
					this.statuss = val.label;
					this.equipStatus = val.value;
				})
			},
			//获取下拉厂站
			getOrginList() {
				this.$u.api.search({
						"algorithmProcessId": "getStationEq",
						"param": {
							"data": {
								"user_uuid": uni.getStorageSync('uuid')
							}
						}
					})
					.then(result => {
						let station = result.data.data.result || [];
						this.station = station.map(item => {
							return {
								value: item.id,
								label: item.structure_name
							};
						});
						if (station.length > 1) {
							//用户是集团的
							this.headOrgin = 1
						} else if (station.length == 1) {
							//用户属于分厂
							this.headOrgin = 0;
						}

					});

			},
			//查询设备列表
			searchQeuipmentInfo() {
				this.loading = false;
				this.$u.api.searchEquipList({
					"algorithmProcessId": "getFalarmCount",
					"param": {
						"data": {
							"station_id": uni.getStorageSync('navId'),
							"status": this.equipStatus,
							"equipName": this.equipName,
							"network_status": this.networkStatus,
							"equipment_typecode": this.equipmentTypecode,
							"parent_name": this.parentName
						}
					}
				}).then(res => {
					const equipInfo = res.data.data.result || [];
					this.equipInfoOne = equipInfo.map(item => ({
						id: item.id,
						equipment_name: item.equipment_name,
						equip_id: item.equip_id,
						equipment_typecode: item.equipment_typecode,
						usetime: item.usetime,
						parent_name: item.parent_name,
						status: item.status,
						network_status: item.network_status,
						isAlarm: item.is_alarm
					}));
					this.getEqImg();
				}).catch(error => {
					console.error(error);
				}).finally(() => {
					this.loading = true;
				});
			},

			getEqImg() {
				// 请求图片数据
				this.$u.api.getEqImg({
					"algorithmProcessId": "getEqImage",
					"param": {
						"data": {}
					}
				}).then(res => {
					const images = res.data.data.result || [];


					this.updateEquipInfo(images);
				}).catch(error => {
					console.error(error);
				});
			},

			updateEquipInfo(images) {
				// 创建图片数据的映射表
				const imageMap = images.reduce((map, img) => {
					map[img.equipment_typecode] = img.image;
					return map;
				}, {});

				// 更新设备信息
				this.equipInfo = this.equipInfoOne.map(item => ({
					...item,
					image: imageMap[item.equipment_typecode] || '/static/index/equipment/smartDevices.png'
				}));
			},

			searchQeuipmentInfo2() {
				this.$u.api.searchEquipList2({
					"algorithmProcessId": "getFalarmCount2",
					"param": {
						"data": {
							"station_id": uni.getStorageSync('navId'),
						}
					}
				}).then(res => {
					const equipInfo2 = res.data.data.result || [];
					this.equipInfo2 = equipInfo2.map(item => ({
						id: item.id,
						equipment_name: item.equipment_name,
						equip_id: item.equip_id,
						equipment_typecode: item.equipment_typecode,
						usetime: item.usetime,
						parent_name: item.parent_name,
						status: item.status,
						network_status: item.network_status,
						isAlarm: item.is_alarm
					}));
				}).catch(error => {
					console.error(error);
				});
			},

			details(id) {
				uni.navigateTo({
					url: '/pages/sys/equipment/details?id=' + id
				});
			}

		},
		onTabItemTap() {
			//在点击底部菜单的时候,获取厂站列表，获取默认厂站的数据
			setTimeout(() => {
				if (this.headOrgin == 1) {
					this.originId = uni.getStorageSync('navId');
					this.equipStatus = '';
					this.orgins = '水厂';
					this.searchQeuipmentInfo();
				} else if (this.headOrgin == 0) {
					this.originId = this.station[0].value;
					this.equipStatus = '';
					this.orgins = '' + this.station[0].label;
					this.searchQeuipmentInfo();
				}
			}, 1000)
		}

	}
</script>
<style lang="scss">
	@import 'style/index.scss';
</style>